﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace RTracker.Models.ErrorLog
{
    public static class ELParser
    {
        /// <summary>
        /// Data Base Error Formatting :
        /// > TTMMAA eg. 124451
        /// Where   12 = Error Type, Defined by 'TT'
        ///         44 = Model Type, Defined by 'MM'
        ///         51 = Specific Argument, Defined by 'AA'
        /// Return string Format :
        /// > Type_Model_Argument eg. IsNull_User_@UserId
        /// 
        /// Default return string:
        /// > UNKNOWN_UNKNOWN_UNKNOWN
        /// where in this all or none can be UNKNOWN.
        /// </summary>
        /// <param name="errorNum">Takes negative int as an input</param>
        /// <returns>Returns a simplified error string</returns>
        public static string DbError(this int errorNum)
        {
            string errorCode = string.Empty;
            string errorMsg = string.Empty;
            errorNum = errorNum / -1;
            int AA = errorNum % 1000;
            int MM = (errorNum / 100) % 100;
            int TT = (errorNum / 10000);
            if (TT != 10)
            {
                errorCode = errorNum.ToString() + "x - Type : " + TT.GetDbErrorType() + "_ Model : " + MM.GetDbErrorModel() + "_ Error Arg : " + AA.GetDbErrorArgument();
            }

            errorMsg = MM.GetUserErrorType() + AA.GetUserErrorMessage();

            return errorMsg;
        }

        private static string GetDbErrorType(this int errorNum)
        {
            if (ELErrorDict.DbErrorText_Type.ContainsKey(errorNum))
            {
                return ELErrorDict.DbErrorText_Type[errorNum];
            }
            return "UNKNOWN";
        }

        private static string GetDbErrorModel(this int errorNum)
        {
            if (ELErrorDict.DbErrorText_Models.ContainsKey(errorNum))
            {
                return ELErrorDict.DbErrorText_Models[errorNum];
            }
            return "UNKNOWN";
        }

        private static string GetDbErrorArgument(this int errorNum)
        {
            if (ELErrorDict.DbErrorText_Arguments.ContainsKey(errorNum))
            {
                return ELErrorDict.DbErrorText_Arguments[errorNum];
            }
            return "UNKNOWN";
        }

        private static string GetUserErrorType(this int errorNum)
        {
            if (ELErrorDict.UserErrorText_Type.ContainsKey(errorNum))
            {
                return ELErrorDict.UserErrorText_Type[errorNum];
            }
            return "UNKNOWN";
        }

        private static string GetUserErrorMessage(this int errorNum)
        {
            if (ELErrorDict.UserErrorText_Message.ContainsKey(errorNum))
            {
                return ELErrorDict.UserErrorText_Message[errorNum];
            }
            return "UNKNOWN";
        }
    }
}